package com.baymax.study.redisson.infrastructure.locks.lock;

import com.baymax.study.redisson.infrastructure.locks.framework.DistributedReadLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public class DistributedReadLockImpl implements DistributedReadLock {
    private final RedissonClient redissonClient;

    public DistributedReadLockImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public boolean forceUnlock(String lockName) {
        return redissonClient.getReadWriteLock(lockName).readLock().forceUnlock();
    }

    @Override
    public boolean isLocked(String lockName) {
        return redissonClient.getReadWriteLock(lockName).readLock().isLocked();
    }

    @Override
    public void lock(String lockName) {
        redissonClient.getReadWriteLock(lockName).readLock().lock();
    }

    @Override
    public boolean tryLock(String lockName, Long waitTime, Long leaseTime, TimeUnit unit) {
        try {
            return redissonClient.getReadWriteLock(lockName).readLock().tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean tryLock(String lockName, Long lockTime, TimeUnit unit) {
        try {
            return redissonClient.getReadWriteLock(lockName).readLock().tryLock(lockTime, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void unlock(String lockName) {
        redissonClient.getLock(lockName).unlock();
    }

    @Override
    public boolean isHeldByCurrentThread(String lockName) {
        return redissonClient.getReadWriteLock(lockName).readLock().isHeldByCurrentThread();
    }
}
